// pages/search/search.js
import request from '../../utils/request'
let isSend = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showKeyword: '',
    hotListData: [], // 热词数组
    searchWord: '', // 搜索的值
    searchList: [], // 模糊搜索的结果
    historyList: [], // 搜索历史记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取placeHolder默认值
    this.getInitData()

    //加载历史记录
    this.setData({
      historyList: wx.getStorageSync('history') || []
    })
  },
  async getInitData() {
    // 获取搜索款默认值
    let {
      data
    } = await request('/search/default');

    // 获取热词
    let {
      data: data2
    } = await request('/search/hot/detail')
    let index = 0
    data2.map(item => {
      item.index = index++
      return item
    })
    this.setData({
      showKeyword: data.showKeyword,
      hotListData: data2
    })
  },
  // 收集表单数据
  handleInput(event) {
    // 输入款的值
    let value = event.detail.value.trim()

    this.setData({
      [event.currentTarget.id]: value
    })
    if (!value) return;

    this.getSearchList();

  },
  async getSearchList() {
    if (isSend) {
      return
    }
    isSend = true;
    // 发送请求获取热搜榜数据
    let {
      searchWord
    } = this.data;
    let {
      result: searchListData
    } = await request('/search', {
      keywords: searchWord,
      limit: 10
    })

    this.saveHistory(searchWord)
    this.setData({
      searchList: searchListData.songs
    })



    setTimeout(async () => {
      isSend = false;
    }, 300)
  },
  saveHistory(searchWord) {
    let {
      historyList
    } = this.data
    // 将搜索的关键字添加到搜索历史记录中
    let searchWordIndex = historyList.indexOf(searchWord)
    if (searchWordIndex !== -1) {
      historyList.splice(searchWordIndex, 1)
    }
    historyList.unshift(searchWord)

    // 将历史记录保存到本地
    wx.setStorageSync('history', historyList)
    this.setData({
      historyList
    })
  },
  // 清空输入框
  handleClear() {
    console.log("clear");
    this.saveHistory(this.data.searchWord)
    this.setData({
      searchWord: ''
    })
  },
  // 清空历史记录
  handleClearHistory(){
    wx.showModal({
      title: '提示',
      content: '确认清空历史记录吗',
      success :(res) =>{
        if (res.confirm) {
          
          wx.removeStorageSync('history')
          this.setData({
            historyList:[]
          })
        } 
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})